package com.dream21th.common.validator;


import com.dream21th.common.ComReq;
import com.dream21th.common.annotation.OwnDefine;
import com.dream21th.common.utils.ThreadData;
import org.hibernate.validator.internal.engine.constraintvalidation.ConstraintValidatorContextImpl;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.reflect.Method;
import java.util.Objects;

public class OwnDefineValidator implements ConstraintValidator<OwnDefine,Object> {
    private OwnDefine ownDefine;

    @Override
    public void initialize(OwnDefine constraintAnnotation) {
        this.ownDefine=constraintAnnotation;
    }

    @Override
    public boolean isValid(Object o, ConstraintValidatorContext constraintValidatorContext) {
        ComReq comReq= (ComReq) ThreadData.DATA.get();
        Object body=comReq.getRequestData();
        try {
            String validClassName = this.ownDefine.checkClass();
            Class validClass=null;
            Object invokeResult=null;
            if("".equals(validClassName) || Objects.isNull(validClassName)){
                validClass=body.getClass();
                Method invoke = validClass.getDeclaredMethod(this.ownDefine.method(), new Class[]{});
                invokeResult = invoke.invoke(body);
            }else{
                validClass=Class.forName(validClassName);
                Object validObject = validClass.newInstance();
                Method invoke=null;
                Class[] paramType=new Class[]{};
                Object[] params=new Object[]{};
                switch (this.ownDefine.paramType()){
                    case Body:
                        paramType= new Class[]{body.getClass()};
                        params=new Object[]{body};
                        break;
                    case ALL:
                        paramType= new Class[]{comReq.getClass()};
                        params=new Object[]{comReq};
                        break;
                    default:
                        break;
                }
                invoke = validClass.getDeclaredMethod(this.ownDefine.method(), paramType);
                invokeResult = invoke.invoke(validObject,params);
            }
            String message=(String)invokeResult;
            if(message!=null && !message.equals("")){
                ((ConstraintValidatorContextImpl)constraintValidatorContext).addMessageParameter("abc",message);
                return false;
            }else {
                return true;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }
}
